package cn.com.dhcc.app.pub.module.usermgr.service;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import cn.com.dhcc.app.core.base.BaseService;
import cn.com.dhcc.app.core.base.CmCommon;
import cn.com.dhcc.app.core.base.Dao;
import cn.com.dhcc.app.core.base.log.LogType;
import cn.com.dhcc.app.core.base.user.LoginUser;
import cn.com.dhcc.app.core.component.db.SingleTransationCircleWithOutResult;
import cn.com.dhcc.app.core.component.db.orm.WhereCondition;
import cn.com.dhcc.app.core.component.log.Log;
import cn.com.dhcc.app.core.component.pager.Pager;
import cn.com.dhcc.app.core.component.pager.PagerData;
import cn.com.dhcc.app.core.exception.DaoException;
import cn.com.dhcc.app.core.exception.NiceException;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.tag.CommonStaticCode.ENTITY_STATUS;
import cn.com.dhcc.app.core.util.NetUtil;
import cn.com.dhcc.app.core.util.SpringUtil;
import cn.com.dhcc.app.core.util.StrUtil;
import cn.com.dhcc.app.pub.core.AppPara.UAMS;
import cn.com.dhcc.app.pub.core.Table;
import cn.com.dhcc.app.pub.core.interceptor.InjectLoginUserInterceptor;
import cn.com.dhcc.app.pub.module.authmgr.service.AuthService;
import cn.com.dhcc.app.pub.module.login.vo.LoginCustomData;
import cn.com.dhcc.app.pub.module.resmgr.service.ResourceService;
import cn.com.dhcc.app.pub.module.usermgr.dao.CmUserMgrDao;
import cn.com.dhcc.app.pub.module.usermgr.vo.UserExt;
import cn.com.dhcc.app.pub.module.usermgr.vo.UserInfoVo;

/**
 * 
 * @author qiao
 * @2013-11-20 @下午3:18:35
 */
@Service("CmUserMgrService")
public class CmUserMgrService extends BaseService {

	Logger logger = Log.getLogger(LogType.BUSILOG);
	
	@Autowired
	private ResourceService resourceService;
	@Autowired
	private CmUserMgrDao dao;
	@Autowired
	AuthService authService;
	@Autowired
	private RelUserRoleInfoService relUserRoleInfoService;

	/**
	 * 获取非同一用户用户信息
	 * @param pager
	 * @param searchParameter 
	 * @return
	 * @throws ServiceException
	 */
	public PagerData<UserInfoVo> listUser(Pager pager, UserInfoVo userInfoVo,String order,String orderName) throws ServiceException {
		try {
			return dao.listUser("获取用户列表", pager, userInfoVo, order, orderName);
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}
	
	/**
	 * 获取用户
	 * @param userCode
	 * @return
	 * @throws ServiceException
	 */
	public LoginUser getUserByUserCode(String userCode,HttpServletRequest request) throws ServiceException {
		return (LoginUser) InjectLoginUserInterceptor.getLoginUserFromSsoUser(request);
	}
	/**
	 * 
	 * @param offset
	 * @param pagerSize
	 * @return {List<HowTo>,total}
	 * @throws ServiceException
	 *//*
	public UserInfoNoSso getUser(SearchParameter searchParameter) throws ServiceException {
		String presql = "SELECT * FROM  "+WSD_TABLE(Table.SYSTABLE.SYS_USER);
		try {
			return CM.getDao().get("根据参数名获取用户", presql,new UserInfoRowWapper(),searchParameter, new Object[]{});
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}*/
	
	public void addUser(final UserInfoVo user) throws ServiceException,NiceException {
		if(user==null)throw new NiceException("缺少参数");
		//user.setId(UUIDGenerator.getUUID());
		try{
			getDao().insertModule("添加用户", user);
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}	
	public void updateUser(UserInfoVo user) throws ServiceException, NiceException {
		if(user==null||!StringUtils.hasText(user.getId()))throw new NiceException("缺少参数");
		try {
			getDao().updateModuleByIdExecuteNull("修改用户", user);
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}
	public UserInfoVo getUserById(String id) throws ServiceException {
		String getUser_sql = "SELECT *  FROM "+WSD_TABLE(Table.SYS_BASE_TABLE.SYS_BASE_USER)+"  WHERE id=?";
		try {
			return getDao().getModule("获取用户信息", getUser_sql,UserInfoVo.class, new Object[]{id});
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}
	public UserInfoVo getUserByName(String userName) throws ServiceException {
		if(StrUtil.isBlank(userName))return null;
		String getUser_sql = "SELECT *  FROM "+WSD_TABLE(Table.SYS_BASE_TABLE.SYS_BASE_USER)+"  WHERE userName=? and status='1'";
		try {
			return getDao().getModule("获取用户信息", getUser_sql,UserInfoVo.class, new Object[]{userName});
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}
	public  LoginUser toSsoUserFromInnerUserInfoVo(UserInfoVo userInfoVo) throws ServiceException  {
		if(userInfoVo==null)return null;
		LoginUser ssoUser = new LoginUser();
		ssoUser.setId(userInfoVo.getId());
		ssoUser.setUserName(userInfoVo.getUserName());
		ssoUser.setFromSso(false);
		try {
			ssoUser.setIp(NetUtil.getRemoteIp(SpringUtil.getRequest()));
		} catch (Exception e) {
			//ignore
		}
		//ssoUser.setPwd(userInfoVo.getPassWd());
		ssoUser.setLoginTime(new Date());
		ssoUser.setUserCode(userInfoVo.getId());
		//ssoUser.setSsoRawUserInfo(userInfoVo);
		ssoUser.setSuperAdmin(false);
		LoginCustomData customData = new LoginCustomData();
		//busiData.setExt1(userInfoVo.getExt1());
		//busiData.setExt2(userInfoVo.getExt2());
		ssoUser.setCustomData(customData);
		//用户角色
		/*List<RoleInfoInner> roleInfos;
		try {
			roleInfos = relUserRoleInfoService.getRoleListByUser(userInfoVo.getId());
		} catch (ServiceException e) {
			throw new ServiceException("获取用户失败", e);
		}*/
		//ssoUser.setRoles(roleInfos);
		//ssoUser.setAuthUserTypes(BaseController.getLoginUserTypeFromUserRole(ssoUser.getRoles()));
		return ssoUser;
	}
	public void deleteUserById(final String id) throws ServiceException {
		try {
			Dao dao = getDao();
			 dao.doInSingleTransationCircle("删除用户", new SingleTransationCircleWithOutResult() {
				@Override
				public void actionInCircle() throws RuntimeException {
					try {
						getDao().delete("删除用户角色关联数据，id[" + id + "]", "DELETE FROM "+WSD_TABLE(Table.SYS_BASE_TABLE.SYS_BASE_REL_USER_ROLE)+"  WHERE user_id = ?", new Object[]{id});
						getDao().delete("删除用户数据，id[" + id + "]", "DELETE FROM "+WSD_TABLE(Table.SYS_BASE_TABLE.SYS_BASE_USER)+"  WHERE id = ?", new Object[]{id});	
					} catch (Exception e) {
						throw new RuntimeException(e);
					}
				}
			});
		} catch (DaoException e) {
			throw new ServiceException("删除用户失败", e);
		}
	}
	
	public boolean isPropertyUnique(final String propertyName, final String newValue, final String oldValue) throws ServiceException{
		if (newValue == null || newValue.equals(oldValue)){
			return true;
		}
		String sql = "SELECT count(*) FROM "+WSD_TABLE(Table.SYS_BASE_TABLE.SYS_BASE_USER)+"  WHERE "+propertyName+" = ?";
		try {
			return getDao().queryForInt("查询"+propertyName+"是否唯一", sql, new Object[]{newValue}) == 0;
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}
	/*public PagerData<UserInteraction> listUserInteraction(Pager pager) throws ServiceException {
		String sql = "select * FROM si_user_interaction";
		try {
			return CM.getDao().getPagerList("获取用户关联表列表", sql, pager, new UserInteractionRowWapper(),new Object[]{});
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}*/
	public void changeUserStatus(String id,ENTITY_STATUS  status) throws ServiceException, NiceException {
		UserInfoVo userInfo = getUserById(id);
		if(userInfo==null){
			throw new NiceException("操作失败，用户已不存在");
		}
		if(status.getCode().equalsIgnoreCase(userInfo.getStatus())){
			throw new NiceException("操作失败，用户已为"+status.getName()+"状态");
		}
		String sql = "update "+WSD_TABLE(Table.SYS_BASE_TABLE.SYS_BASE_USER)+"  set status=? where id=?";
		try {
			 getDao().update("修改id["+userInfo.getUserName()+"]用户为："+status.getName(), sql,new Object[]{status.getCode(),id});
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}
	/**
	 * 获取当前用户的所有资源菜单
	 * @param inits 
	 * @param userId
	 * @return
	 * @throws ServiceException
	 *//*
	public String getJobResourceTreeDataForInit(LoginUser userinfo, final List<String> inits) throws ServiceException {
		final boolean isAdmin = userinfo.isSuperAdmin();
		final List<String> res_ids = new ArrayList<String>();
		if(!isAdmin){
			String getUserResource_sql = 
					" SELECT　RESOURCE_ID　" +
					" FROM "+WSD_TABLE(Table.SYSTABLE.SYS_JOB_ROLE)+"  sjr,"+WSD_TABLE(Table.SYSTABLE.SYS_ROLE_RESOURCE)+"  srr" +
					" WHERE sjr.ROLE_ID=srr.ROLE_ID ";
			SearchParameter parameter = new SearchParameter();
			parameter.setWithWhere(false);
			SsoUser ssoUser = (SsoUser)userinfo;
			parameter.addEqual("sjr.job_code", ssoUser.getJobCodes());
			try {
				List<String> res_ids_db = CM.getDao().list("获取用户所有的资源列表", getUserResource_sql, new SingleColumnRowMapper<String>(String.class),parameter,null);
				res_ids.addAll(res_ids_db);
			} catch (DaoException e) {
				throw new ServiceException(e);
			}
			if(res_ids==null||res_ids.isEmpty())return "";
			
		}
		
		return resourceService.getResource(new ResourceFilter() {
			@Override
			public boolean selectCurrentNode(UrlResource resource ) {
				return inits.contains(resource.getId());
			}
			
			@Override
			public boolean removeCurrentNode(UrlResource resource) {
				return ("1".equals(resource.getHidden())||!isAdmin&&!res_ids.contains(resource.getId()))||(UrlResource.ResourceType.ACTION.getType().equals(resource.getType()));
			}
			@Override
			public boolean openCurrentNode(UrlResource resource) {
				return inits.contains(resource.getId());
			}
			@Override
			public boolean nocheck(UrlResource resource) {
				try {
					return !(!(UrlResource.ResourceType.ACTION.getType().equals(resource.getType()))&&(resourceService.isLastMenu(resource.getId())));
				} catch (ServiceException e) {
					logger.error(e);
					return true;
				}
				//return !resource.getType().equals(UrlResource.ResourceType.MENUNODE2.getType());
			}
		});
	}*/
	public UserExt getUserExt(WhereCondition searchParameter) throws ServiceException {
		UserExt ext = null;
		try {
			 ext = CmCommon.getDao().getModule("获取用户扩展信息", UserExt.class, searchParameter);
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
		return ext;
	}
	public void addUserExt(UserExt userExt) throws ServiceException {
		try {
			CmCommon.getDao().insertModule("添加用户扩展信息", userExt);
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}
	public void updateUserExt(UserExt userExt,WhereCondition searchParameter) throws ServiceException {
		try {
			CmCommon.getDao().updateModule("修改用户扩展信息", userExt, searchParameter);
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}
	/*public String getResourceTreeDataForInit(LoginUser userinfo, final List<String> inits) throws ServiceException {
		final boolean isAdmin = userinfo.isSuperAdmin();
		final List<String> res_ids = new ArrayList<String>();
		if(!isAdmin){
			String getUserResource_sql = 
					" SELECT　RESOURCE_ID　" +
					" FROM "+WSD_TABLE(SYS_BASE_TABLE.SYS_USER_ROLE)+"  sur,"+WSD_TABLE(SYS_BASE_TABLE.SYS_BASE_ROLE_RESOURCE)+"  srr" +
					" WHERE sur.ROLE_ID=srr.ROLE_ID and sur.user_id=?";
			
			try {
				List<String> res_ids_db = CM.getDao().list("获取用户所有的资源列表", getUserResource_sql, new SingleColumnRowMapper<String>(String.class), new Object[]{userinfo.getId()});
				res_ids.addAll(res_ids_db);
			} catch (DaoException e) {
				throw new ServiceException(e);
			}
			if(res_ids==null||res_ids.isEmpty())return "";
			
		}
		
		return resourceService.getResource(new ResourceFilter() {
			@Override
			public boolean selectCurrentNode(UrlResource resource ) {
				return inits.contains(resource.getId());
			}
			
			@Override
			public boolean removeCurrentNode(UrlResource resource) {
				return ("1".equals(resource.getHidden())||!isAdmin&&!res_ids.contains(resource.getId()))||(UrlResource.ResourceType.ACTION.getType().equals(resource.getType()));
			}
			@Override
			public boolean openCurrentNode(UrlResource resource) {
				return inits.contains(resource.getId());
			}
			@Override
			public boolean nocheck(UrlResource resource) {
				try {
					return !(!(UrlResource.ResourceType.ACTION.getType().equals(resource.getType()))&&(resourceService.isLastMenu(resource)));
				} catch (ServiceException e) {
					logger.error(e);
					return true;
				}
				//return !resource.getType().equals(UrlResource.ResourceType.MENUNODE2.getType());
			}
		});
	}*/
	public void updateUserInitAction(String uid, String resourceId) throws ServiceException {
		WhereCondition searchParameter = new WhereCondition();
		searchParameter.where1Eq1();
		searchParameter.andEq("USER_ID", uid);
		UserExt userExt = getUserExt(searchParameter);
		if(userExt==null){
			userExt = new UserExt();
			userExt.setUserId(uid);
			userExt.setInitResourceId(resourceId);
			addUserExt(userExt);
		}else{
			userExt.setInitResourceId(resourceId);
			updateUserExt(userExt, searchParameter);
		}
	}
	public boolean isPasswdExist(String id, String passwd) throws ServiceException {
		if (passwd == null || passwd==""){
			return false;
		}
		String sql = "SELECT count(*) FROM "+WSD_TABLE(Table.SYS_BASE_TABLE.SYS_BASE_USER)+"  WHERE id = ? and passwd=?";
		Integer n = null;
		try {
			n = getDao().queryForInt("查询密码是否存在", sql,new Object[]{id,passwd});
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
		if(n==null||n==0)return false;
		return true;
	}
	public void updateUserPasswd(String userId,String newPwd) throws ServiceException, NiceException {
		if(!StringUtils.hasText(newPwd))throw new NiceException("缺少参数");
		UserInfoVo userInfoVo = getUserById(userId);
		if(userInfoVo==null){
			throw new NiceException("用户不存在");
		}
		String updateUser_sql = "UPDATE "+WSD_TABLE(Table.SYS_BASE_TABLE.SYS_BASE_USER)+"  SET passwd=?,modified=? where id=?";
		try {
			getDao().update("修改用户密码", updateUser_sql, new Object[]{newPwd,new Date(),userId});
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}
	/**
	 * 获取配置文件里面的超级管理员
	 * @return
	 */
	public static LoginUser getSuperAdmin(){
		String superStr = UAMS.ADMIN_INFO_STR;
		if (!StringUtils.hasText(superStr)) {//如果超级管理员信息为null，则证明没有SsoUser
			return null;
		}
		LoginUser userInfoNoSso = new LoginUser();
		LoginCustomData customData = new LoginCustomData();
		userInfoNoSso.setCustomData(customData);
		String[] args = superStr.split("/");
		for (int i = 0; i < args.length; i++) {
			userInfoNoSso.setId(args[0]);
			userInfoNoSso.setFromSso(false);
			userInfoNoSso.setUserName(args[1]);
			//userInfoNoSso.setPwd(args[2]);
			userInfoNoSso.setSuperAdmin(true);
			userInfoNoSso.setUserCode(userInfoNoSso.getUserName());
			customData.setAdminPwd(args[2]);
			if(UAMS.SSO_ENABLED&&UAMS.isSLUAMS()){
				if(StrUtil.isNotBank(args[3])){
					customData.setAdminOrgCode(args[3]);
					customData.setOrgCode(args[3]);
				}
			}
			
		}
		return userInfoNoSso;
	}
	/**
	 * 是否合法的统一用户管理
	 * @param userCode
	 * @param pwd
	 * @return
	 * @throws ServiceException
	 */
	public boolean  isValidUUmsUser(String userCode,String pwd) throws ServiceException{
		return false;
		/*try {
		return 	uumsIntegrateService.isValidUumsUser(userCode, pwd);
		} catch (ServiceException e) {
			throw new ServiceException(e);
		}*/
	}
}
